﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FyCacheClient.Pool
{
    internal class ConnectPool
    {
        private static List<Connect> FreeConnections = new List<Connect>(10);

        /// <summary>
        /// 获取空闲连接
        /// </summary>
        /// <returns></returns>
        internal static Connect GetFreeConnect(IPAddress iPAddress, int port)
        {
            Connect connect = null;
            try
            {
                lock (FreeConnections)
                {
                    if (FreeConnections.Count > 0)
                    {
                        foreach (var item in FreeConnections)
                        {
                            if (item.Client.SimSocketInfo.RemoteEndPoint.Address == iPAddress && item.Client.SimSocketInfo.RemoteEndPoint.Port == port && item.IsUsed == false)
                            {
                                connect = item;
                                connect.IsUsed = true;
                                break;
                            }
                        }
                    }

                    if (connect == null)
                    {
                        connect = new Connect();
                        connect.IsUsed = true;
                        connect.Client = new FySystem.Net.SimSocket.SimClient(iPAddress, port);
                        connect.Client.Connect();
                        FreeConnections.Add(connect);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return connect;
        }

        /// <summary>
        /// 将正在用的连接放回连接池
        /// </summary>
        /// <param name="connect"></param>
        internal static void FreeConnect(Connect connect)
        {
            try
            {
                if (connect == null)
                    return;

                connect.Client.OnReceive = null;
                connect.IsUsed = false;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
